//
//  CZEmoticonToolBar.swift
//  weiBo
//
//  Created by apple on 16/5/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum CZEmoticonToolBarButtonType: Int {
    case Normal = 1000
    case Emoji = 1001
    case Lxh = 1002
}

class CZEmoticonToolBar: UIStackView {
    //记录最后一次点击的按钮
    var lastClickBtn: UIButton?
    
    //点击回调的闭包
    var didSelectedEmoticonButtonClosure: ((type: CZEmoticonToolBarButtonType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setUpUI() {
        
        //设置排列顺序
        axis = .Horizontal
        //填充方式
        distribution = .FillEqually
    
        addChildButton("默认", bgImageName: "compose_emotion_table_left", type: .Normal)
        addChildButton("Emoji", bgImageName: "compose_emotion_table_mid", type:  .Emoji)
        addChildButton("浪小花", bgImageName: "compose_emotion_table_right", type: .Lxh)
    }
    
    
    //定义按钮
    private func addChildButton(title: String, bgImageName: String, type:CZEmoticonToolBarButtonType) {
        let btn = UIButton()
        btn.tag = type.rawValue
        btn.setTitle(title, forState: .Normal)
        btn.addTarget(self, action: "emoticonButtonClick:", forControlEvents: .TouchUpInside)
        //  设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Selected)
        //  字体大小
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        //  设置背景图片
        btn.setBackgroundImage(UIImage(named: "\(bgImageName)_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "\(bgImageName)_selected"), forState: .Selected)
        //  去掉高亮效果
        btn.adjustsImageWhenHighlighted = false
        //  添加按钮
        addArrangedSubview(btn)
        
        //默认选中状态
        if type == .Normal {
            lastClickBtn?.selected = false
            btn.selected = true
            lastClickBtn = btn
        }
    }
    
    @objc private func emoticonButtonClick(button: UIButton){
        if button == lastClickBtn {
            return
        }
        
        lastClickBtn?.selected = false
        
        button.selected = true
        
        lastClickBtn = button
        
        let type = CZEmoticonToolBarButtonType(rawValue: button.tag)!
        didSelectedEmoticonButtonClosure?(type: type)
    
    }
    
    //根据传入的section决定选中的按钮
    func selectEmotionButtonWithSection(section: Int) {
        
        if section + 1000 == lastClickBtn?.tag {
            return
        }
        
        
        let btn = viewWithTag(section + 1000) as! UIButton
        lastClickBtn?.selected = false
        btn.selected = true
        lastClickBtn = btn

    }
    
    
    
}
